package com.codechuan.didi_web.controller;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.didi_web.entity.SysCarInfo;
import com.codechuan.didi_web.entity.SysUserConfig;
import com.codechuan.didi_web.entity.SysUserToken;
import com.codechuan.didi_web.service.SysUserAccountService;
import com.codechuan.didi_web.service.SysUserConfigService;
import com.codechuan.didi_web.service.SysUserTokenService;
import com.codechuan.didi_web.service.ThreadManagerService;
import com.codechuan.didi_web.utils.DiDiHttpUtil;
import com.codechuan.didi_web.utils.ResultUtils;
import com.codechuan.didi_web.vo.ResultVO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/threadManager")
public class ThreadManagerController {

    @Resource
    private ThreadManagerService threadManagerService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SysUserTokenService sysUserTokenService;
    @Resource
    private SysUserConfigService sysUserConfigService;
    @Resource
    private SysUserAccountService sysUserAccountService;


    /**
     * @param account       用户账户/卡密
     * @param sysUserConfig 刷单参数实体类
     * @return 返回启动成功或停止成功
     * @Deprecated 执行抢单
     */
    @GetMapping(value = "/startOrEndThread")
    private ResultVO<Object> startOrEndThread(@RequestHeader("token") String account, SysUserConfig sysUserConfig) {

        // 获取自己平台token里面的卡密来取滴滴的token
        String accountData = redisTemplate.opsForValue().get(account);
        if (accountData == null) {
            return ResultUtils.error(500, "登录已过期请重新登录", null);
        }
        JSONObject jsonObject = JSONObject.parseObject(accountData);
        // 取出重新赋值
        account = jsonObject.getString("keyNumber");
        // 获取滴滴的主号token
        String ticket = sysUserTokenService.selectMainTokenByAccount(account);
        if (ticket == null) {
            return ResultUtils.error(500, "该卡密未绑定token", null);
        }
        // 获取滴滴的小号token集合
        List<String> minTokenList = sysUserTokenService.selectMiniTokenListByAccount(account);
        if (sysUserConfig.getCityId() == 0)
            return ResultUtils.error(500,"请先定位城市","");
        // 校验参数
        if (sysUserConfig.getStartTime() == null || Objects.equals(sysUserConfig.getStartTime(), ""))
            return ResultUtils.error(500, "参数设置错误,开始时间不能为空!", null);
        if (sysUserConfig.getEndTime() == null || Objects.equals(sysUserConfig.getEndTime(), ""))
            return ResultUtils.error(500, "参数设置错误,结束时间不能为空!", null);
        if (sysUserConfig.getJkJl() == null || Objects.equals(sysUserConfig.getJkJl(), ""))
            return ResultUtils.error(500, "参数设置错误,接客距离不能为空!", null);
        if (sysUserConfig.getDxCheckBox().equals("false") && sysUserConfig.getPcCheckBox().equals("false"))
            return ResultUtils.error(500, "参数设置错误,独享和拼车必须选择一个!", null);
        if (sysUserConfig.getSxNumber() == null)
            return ResultUtils.error(500, "参数设置错误,刷新延时不能为空!", null);
        String sort = "smart_sort";
        // 设置排序规则
        switch (sysUserConfig.getValue2()){
            case "b":
                sort = "smart_sort";
                break;
            case "c":
                sort = "price_sort";
                break;
            case "d":
                sort = "time_sort";
                break;
            case "e":
                sort = "distance_sort";
                break;
        }
        // 设置刷单类型
        switch (String.valueOf(sysUserConfig.getValue1())){
            // 大厅
            case "1":
                sysUserConfig.setQueryType("0");
                break;
            // 行程
            case "2":
                sysUserConfig.setQueryType("1");
                break;
        }

        String msg;
        if (sysUserConfig.getQueryType().equals("0")) {
            // 创建大厅请求参数
            String token = URLEncoder.encode(ticket);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("access_key_id", 2);
            hashMap.put("route_id", 0);
            hashMap.put("app_version", "6.8.8");
            hashMap.put("lng", sysUserConfig.getLng());
            hashMap.put("address_select", new String[0]);
            hashMap.put("session_id", 0);
            HashMap<String, Object> city_center = new HashMap<>();
            city_center.put("lat", sysUserConfig.getLat());
            city_center.put("lng", sysUserConfig.getLng());
            hashMap.put("city_center", city_center);
            hashMap.put("token", token);
            hashMap.put("sort_type", sort); // 排序规则 smart_sort 智能排序 price_sort 价格最高 time_sort 时间最早 distance_sort 距离最近
            hashMap.put("city_name", sysUserConfig.getCityName());
            hashMap.put("tab_id", 2);
            hashMap.put("filter_group", new String[0]);
            hashMap.put("page_index", 0);
            hashMap.put("to_city_id", 0);
            hashMap.put("lat", sysUserConfig.getLat());
            hashMap.put("city_id", sysUserConfig.getCityId());
            // 保存配置到数据库
            sysUserConfig.setKeyNumber(account);
            sysUserConfigService.insertConfig(sysUserConfig);
            msg = threadManagerService.startOrEndThread(account, ticket, hashMap, sysUserConfig, minTokenList);
            // 修改用户表里面的状态
            sysUserAccountService.updateAccountQdStatus(account, msg.equals("启动成功") ? 1 : 0);
            return ResultUtils.success(null, msg);
        } else {
            // 保存配置到数据库
            sysUserConfig.setKeyNumber(account);
            sysUserConfigService.insertConfig(sysUserConfig);
            // 修改用户表里面的状态
            msg = threadManagerService.startOrEndThread(account, ticket, null, sysUserConfig, minTokenList);
            // 创建行程请求参数
            sysUserAccountService.updateAccountQdStatus(account, msg.equals("启动成功") ? 1 : 0);
            return ResultUtils.success(null, msg);
        }
    }

    /**
     * @param account 用户账户/卡密
     * @param ticket  用户token
     * @return 返回查询到的行程列表
     * @Deprecated 获取自己发布的行程列表
     */
    @GetMapping(value = "/getMySubmitSchedule")
    private ResultVO<Object> getMySubmitSchedule(String account, String ticket) {
        return threadManagerService.getMySubmitSchedule(account, ticket);
    }

    /**
     * @param phone 手机号
     * @return 返回发送结果
     * @Deprecated 滴滴微信小程序发送短信验证码
     */
    @GetMapping(value = "/sendSms")
    private ResultVO<Object> sendSms(String phone) {
        return threadManagerService.sendSms(phone);
    }

    /**
     * @param phone 手机号
     * @param code  验证码
     * @param token token
     * @param type  滴滴账户类型 0主号 1小号
     * @return 返回发送结果
     * @Deprecated 滴滴微信小程序登录
     */
    @GetMapping(value = "/loginDiDi")
    private ResultVO<Object> loginDiDi(String phone, String code, @RequestHeader("token") String token, String type) {
        return threadManagerService.loginDiDi(phone, code, token, type);
    }

    /**
     * @param address 地址
     * @return 返回经纬度和cityId
     * @Deprecated 虚拟定位
     */
    @GetMapping(value = "/virtualPositioning")
    private ResultVO<Object> virtualPositioning(String address) {
        return threadManagerService.virtualPositioning(address);
    }

    /**
     * @param token 滴滴token
     * @Deprecated 删除用户token
     */
    @GetMapping(value = "/deleteToken")
    private ResultVO<Object> deleteToken(String token) {
        return threadManagerService.deleteToken(token);
    }


}
